#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
 

#define MAXLINE 1024
#define CLIENT_FIFO "client.fifo"
#define SERVER_FIFO "server.fifo"

 

//允许用户读、用户写、组成员读和其他用户读

#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
void server(int ,int);

 

int main(int argc, char **argv)

{

    int     readfd, writefd;

    

    //创建服务器FIFO

    if((mkfifo(SERVER_FIFO, FILE_MODE) < 0) && (errno != EEXIST))
    {

        printf("can't create %s", SERVER_FIFO);

        exit(0);

    }
    printf("create server fifo successful\n");
    

    //注意打开来读和打开来写的顺序，否则服务器会与客户端互相阻塞，构成死锁

    //打开服务器FIFO（阻塞直到客户端以写的方式打开）

    readfd = open(SERVER_FIFO, O_RDONLY, 0);
    if(readfd<0)
    {
           printf("client failure\n");
    }
    printf("Client is connected!\n");
   
     writefd = open(CLIENT_FIFO, O_WRONLY, 0);
    if(writefd<0)
    {
           printf("write failure\n");
 
    }
    printf("start write\n");
   
    server(readfd, writefd);

    //删除服务器的FIFO

    unlink(SERVER_FIFO);
    exit(0);

}

 

void server(int readfd,int writefd)
{

    int               fd;
    ssize_t           n;
    char              buff[MAXLINE + 1];

 

    //接收客户端发送的数据

    if ((n = read(readfd, buff, MAXLINE)) == 0)
    {

       printf("end-of-file while reading pathname\n");

       return;

    }

 

    //添加结束符

    buff[n] = '\0';

 

    //根据接收到的文件名打开文件

    if ( (fd = open(buff, O_RDONLY)) < 0)
    {

        //打开文件失败

        snprintf(buff + n, sizeof(buff) - n, ": cant't open, %s\n", strerror(errno));

        n = strlen(buff);

        write(writefd, buff, n);

     }
     else
    {

        //打开文件成功，读取文件内容发送给客户端

        while ( (n = read(fd, buff, MAXLINE)) > 0)

               write(writefd, buff, n);
      
        close(fd);

    }

}

 

